package com.zhangfb95.crosschain.infra.controller.starter.httplog;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @author zhangfb
 */
@ControllerAdvice
@Slf4j
public class DefaultResponseBodyAdvice implements ResponseBodyAdvice {

    @Autowired
    private StarterProperties properties;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (properties.canLog(request.getURI().getPath())) {
            if (Objects.equals(properties.getLevel(), "DEBUG")) {
                log.debug("Response body: " + Util.toJsonString(body));
            } else {
                log.info("Response body: " + Util.toJsonString(body));
            }
        }
        return body;
    }
}
